import * as THREE from 'three';
export default class ModelAnimationController {
    constructor(model, animations) {
        this.mixer = new THREE.AnimationMixer(model);
        this.actions = new Map();
        this.animationDurations = {};

        // 初始化所有动画动作
        animations.forEach(clip => {
            this.actions.set(clip.name, this.mixer.clipAction(clip));
            this.animationDurations[clip.name] = clip.duration;
        });
    }

    /**
     * 播放指定动画
     * @param {string} animationName 动画名称
     * @param {object} options 配置选项
     */
    play(animationName, options = {}) {
        if (!this.actions.has(animationName)) {
            console.warn(`动画"${animationName}"不存在`);
            return null;
        }

        // 停止当前所有动画
        this.stopAll();

        const action = this.actions.get(animationName);
        const duration = this.animationDurations[animationName];

        // 基础配置
        action.reset();
        action.clampWhenFinished = options.clamp !== false; // 默认保持在最后一帧
        action.loop = options.loop ? THREE.LoopRepeat : THREE.LoopOnce;
        action.timeScale = options.speed || 1;

        // 特殊效果配置
        if (options.fadeIn) {
            action.fadeIn(options.fadeIn);
        }

        // 播放动画
        action.play();

        // 返回控制接口
        return {
            action,
            duration,
            stop: () => action.stop(),
            onComplete: (callback) => {
                action._onComplete = callback;
            }
        };
    }

    /**
     * 停止所有动画
     */
    stopAll() {
        this.actions.forEach(action => action.stop());
    }

    /**
     * 更新动画混合器
     * @param {number} delta 时间增量
     */
    update(delta) {
        this.mixer.update(delta);

        // 检测动画完成事件
        this.actions.forEach(action => {
            if (action._onComplete && !action.isRunning()) {
                action._onComplete();
                action._onComplete = null;
            }
        });
    }

    /**
     * 获取动画列表
     */
    getAnimationList() {
        return Array.from(this.actions.keys());
    }
}